import axios from 'axios'
import type { AxiosResponse } from 'axios'
import useUserStore from '@/store/user'

let userStore: any = undefined

// 创建实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
})

//  请求拦截
service.interceptors.request.use(
    config => {
        if(!userStore){
            userStore = useUserStore()
        }
        // 请求头中添加token传递
        const token = userStore.token
        if(token){
            config.headers.Authorization = token
        }
        return config
    }
)

// 响应拦截
service.interceptors.response.use(
    (response: AxiosResponse<IResponseData>) => {
        const { status, data: responseDate } = response
        if(status >= 200 && status < 300){
            const {code, data, message} = responseDate
            if(code === 200){
                return data
            }
            return Promise.reject(new Error(message))
        }
    }
)

export default service